const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    let id = 0;
    let gold = 1000000;
    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--id' && args[i + 1]) id = parseInt(args[i + 1], 10);
        if (args[i] === '--gold' && args[i + 1]) gold = parseInt(args[i + 1], 10);
    }
    if (!id) {
        console.error('用法: node scripts/grant-gold.js --id 2001 [--gold 500000]');
        process.exit(1);
    }

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        const [res] = await conn.execute('UPDATE character_resources SET gold = ? WHERE characterId = ?', [gold, id]);
        console.log(`已为角色 ${id} 设定 gold=${gold}，影响行数=${res.affectedRows}`);
    } catch (e) {
        console.error('加金币失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
